package com.liyingtao.servlet;

import com.liyingtao.bean.News;
import com.liyingtao.bean.Page;
import com.liyingtao.biz.NewsService;
import com.liyingtao.util.GetTotalPage;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet("/toMainPageServlet")
public class toMainPageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword=request.getParameter("keyword");
        String nowPage=request.getParameter("pageIndex");
        if(nowPage==null){
            nowPage="1";
        }
        int pageIndex=Integer.parseInt(nowPage);

        NewsService newsservice=new NewsService();

        int count=newsservice.getAllPage(keyword);
        int totalPage=GetTotalPage.getTotalPage(count,GetTotalPage.PAGESIZE);

        if(pageIndex<1){
            pageIndex=1;
        }
        if (pageIndex>totalPage){
            pageIndex=totalPage;
        }

        Page page=new Page();
        page.setStartPage(GetTotalPage.PAGESIZE*(pageIndex-1));
        page.setEndPage(GetTotalPage.PAGESIZE);
        page.setKeyword(keyword);

        List<News> newsList= newsservice.getNewsByPage(page);
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session=request.getSession();
        session.setAttribute("keyword",keyword);
        request.setAttribute("newsList",newsList);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("totalPages",totalPage);

        request.getRequestDispatcher("main.jsp").forward(request,response);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
